package com.rk.kbk.controller;

import com.rk.kbk.common.FailException;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.controller.util.PayUtils;
import com.rk.kbk.controller.util.alipay.util.AlipayNotify;
import com.rk.kbk.controller.util.wxpay.util.WXpayCore;
import com.rk.kbk.controller.util.wxpay.util.WXpayXmlUtils;
import com.rk.kbk.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 支付接口类
 * Created by bin on 2017/3/23.
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/money")
public class MoneyController {
    private Logger log = Logger.getLogger(this.getClass());
    public static String alinotify = "/api/money/alipay/succ";
    public static String wxnotify = "/api/money/wxpay/succ";

    @Autowired
    private UserService userService;

    /**
     * 支付宝支付
     * @param money 金额(元)
     * @param request 、
     * @return 、
     */
    @RequestMapping(value = "/alipay",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String getAlipayOrderSign(Double money, HttpServletRequest request) {
        log.debug("支付宝支付");
        String sym = request.getRequestURL().toString().split("/api/")[0];
        Long userId = userService.currentUserId();
        String trade_no = (userId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
        String stringStringMap = null;
        try {
            stringStringMap =  PayUtils.AliPay(trade_no, money, "测试充值", "测试充值—", sym + alinotify);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (stringStringMap != null) {
            //return JsonResp.ok("成功", stringStringMap);
            return stringStringMap;
        }else{
            throw new FailException();
        }
    }

    /**
     * 微信支付
     * @param money 金额(元)
     * @param request 、
     * @return 、
     */
    @RequestMapping(value = "/wxpay",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getWxpayOrderSign(Double money, HttpServletRequest request,Long userId) {
        log.debug("微信支付");
        String sym = request.getRequestURL().toString().split("/api/")[0];
      //  Long userId= userService.currentUserId();
        String trade_no = (userId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
        Map map;
//        String json=null;
        map = PayUtils.WxPay(trade_no, money, "说明", sym + wxnotify);
        if (map != null) {
            return JsonResp.ok("成功", map);
        }else{
            throw new FailException();
        }
    }

    @RequestMapping(value = "/alipay/succ",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String alipaySucc(HttpServletRequest request) throws IOException {
        log.debug("支付宝支付回调");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //String out_trade_no = request.getParameter("out_trade_no");// 商户订单号

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        //String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号

        //String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        if(AlipayNotify.verify(params)){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                String total_fee = params.get("total_fee");
                Long userId = Long.valueOf(params.get("out_trade_no").split("a")[0]);

                //自己逻辑处理
                //updateUserPay(userId, total_fee);

                return "success";
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//验证失败
            log.debug("+++++++++++++++++++=验证失败");
            return "fail";
        }
        return "fail";
    }

    @RequestMapping(value = "/wxpay/succ",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String wxpaySucc(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            // ------------------------------

            String total_fee = params.get("total_fee");
            double v = Double.valueOf(total_fee) / 100;
            Long userId = Long.valueOf(params.get("out_trade_no").split("a")[0]);

            //updateUserPay(userId, String.valueOf(v));

            // 处理业务完毕
            // ------------------------------
            return "success";
        }
    }

}
